// pages/customer-service/customer-service.js
const app = getApp()

Page({
  data: {
    messages: [],
    inputText: '',
    scrollTop: 0,
    scrollIntoView: '',
    sessionId: null,
    userInfo: {},
    isTyping: false,
    loading: false,
    sessionStatus: '',
    quickReplies: [
      '你好，我想咨询一下',
      '订单问题',
      '物流查询',
      '退换货',
      '商品咨询'
    ],
    showQuickReplies: true
  },

  onLoad(options) {
    this.getUserInfo()
    this.initCustomerService()
  },

  onShow() {
    // 页面显示时刷新消息并标记已读
    if (this.data.sessionId) {
      this.loadMessages()
      this.markSessionMessagesAsRead()
    }
  },

  onUnload() {
    // 页面卸载时断开连接
    this.disconnectWebSocket()
  },

  // 获取用户信息
  getUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || {}
    this.setData({ userInfo })
  },

  // 初始化客服服务
  async initCustomerService() {
    this.setData({ loading: true, sessionStatus: '正在连接客服...' })
    
    try {
      // 创建或获取客服会话
      const session = await this.createOrGetSession()
      this.setData({ 
        sessionId: session.id,
        loading: false,
        sessionStatus: ''
      })
      
      // 加载历史消息
      await this.loadMessages()
      
      // 连接WebSocket
      this.connectWebSocket()
      
    } catch (error) {
      console.error('初始化客服失败:', error)
      this.setData({ 
        loading: false,
        sessionStatus: '连接失败，请重试'
      })
      wx.showToast({
        title: '连接客服失败',
        icon: 'error'
      })
    }
  },

  // 创建或获取客服会话
  createOrGetSession() {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token')
      
      wx.request({
        url: `${app.globalData.apiUrl}/api/CustomerServiceSession`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          subject: '用户咨询',
          source: '小程序'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data.data)
          } else {
            reject(new Error(res.data.message || '创建会话失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 加载消息历史
  loadMessages() {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token')
      
      wx.request({
        url: `${app.globalData.apiUrl}/api/CustomerServiceMessage`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        },
        data: {
          sessionId: this.data.sessionId,
          pageSize: 50
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const messages = res.data.data || []
            this.setData({ 
              messages: messages.map(msg => ({
                ...msg,
                createdAt: this.formatTime(msg.createdAt)
              }))
            })
            this.scrollToBottom()
            resolve(messages)
          } else {
            reject(new Error(res.data.message || '加载消息失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 连接WebSocket
  connectWebSocket() {
    const token = wx.getStorageSync('token')
    
    wx.connectSocket({
      url: `ws://localhost:5000/customerServiceHub?access_token=${token}`,
      success: () => {
        console.log('WebSocket连接成功')
      },
      fail: (error) => {
        console.error('WebSocket连接失败:', error)
      }
    })

    wx.onSocketOpen(() => {
      console.log('WebSocket连接已打开')
      // 加入会话
      wx.sendSocketMessage({
        data: JSON.stringify({
          type: 'JoinSession',
          sessionId: this.data.sessionId.toString()
        })
      })
    })

    wx.onSocketMessage((res) => {
      try {
        const data = JSON.parse(res.data)
        this.handleWebSocketMessage(data)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    })

    wx.onSocketError((error) => {
      console.error('WebSocket错误:', error)
      this.setData({ sessionStatus: '连接异常' })
    })

    wx.onSocketClose(() => {
      console.log('WebSocket连接已关闭')
      this.setData({ sessionStatus: '连接已断开' })
    })
  },

  // 处理WebSocket消息
  handleWebSocketMessage(data) {
    switch (data.type) {
      case 'ReceiveMessage':
        const newMessage = {
          ...data.message,
          createdAt: this.formatTime(data.message.createdAt)
        }
        this.setData({
          messages: [...this.data.messages, newMessage]
        })
        this.scrollToBottom()
        
        // 自动标记消息为已读
        if (newMessage.senderType !== 'user') {
          this.markMessageAsRead(newMessage.id)
        }
        break
        
      case 'MessagesRead':
        // 更新消息已读状态
        const updatedMessages = this.data.messages.map(msg => {
          if (data.MessageIds.includes(msg.id)) {
            return { ...msg, isRead: true, readAt: data.ReadAt }
          }
          return msg
        })
        this.setData({ messages: updatedMessages })
        break
        
      case 'TypingStatus':
        this.setData({ isTyping: data.isTyping })
        if (data.isTyping) {
          this.scrollToBottom()
        }
        break
        
      case 'SessionStatusChanged':
        this.setData({ sessionStatus: this.getStatusText(data.status) })
        break
    }
  },

  // 断开WebSocket连接
  disconnectWebSocket() {
    wx.closeSocket()
  },

  // 发送消息
  async sendMessage() {
    const content = this.data.inputText.trim()
    if (!content || !this.data.sessionId) return

    try {
      const token = wx.getStorageSync('token')
      
      // 先添加到本地消息列表
      const tempMessage = {
        id: Date.now(),
        content,
        messageType: 'text',
        senderType: 'user',
        createdAt: this.formatTime(new Date()),
        sessionId: this.data.sessionId
      }
      
      this.setData({
        messages: [...this.data.messages, tempMessage],
        inputText: ''
      })
      this.scrollToBottom()

      // 发送到服务器
      wx.request({
        url: `${app.globalData.apiUrl}/api/CustomerServiceMessage/send`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          sessionId: this.data.sessionId,
          messageType: 'text',
          content
        },
        success: (res) => {
          if (res.statusCode !== 200) {
            wx.showToast({
              title: '发送失败',
              icon: 'error'
            })
          }
        },
        fail: () => {
          wx.showToast({
            title: '发送失败',
            icon: 'error'
          })
        }
      })

      // 通过WebSocket发送
      wx.sendSocketMessage({
        data: JSON.stringify({
          type: 'SendMessage',
          sessionId: this.data.sessionId.toString(),
          message: {
            messageType: 'text',
            content
          }
        })
      })
      
    } catch (error) {
      console.error('发送消息失败:', error)
      wx.showToast({
        title: '发送失败',
        icon: 'error'
      })
    }
  },

  // 发送快捷回复
  sendQuickReply(e) {
    const content = e.currentTarget.dataset.content
    this.setData({ inputText: content })
    this.sendMessage()
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.uploadImage(tempFilePath)
      }
    })
  },

  // 选择文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        const file = res.tempFiles[0]
        if (file.size > 10 * 1024 * 1024) {
          wx.showToast({
            title: '文件大小不能超过10MB',
            icon: 'none'
          })
          return
        }
        this.uploadFile(file.path, file.name, file.size)
      }
    })
  },

  // 上传图片
  uploadImage(filePath) {
    wx.showLoading({ title: '上传中...' })
    
    wx.uploadFile({
      url: `${app.globalData.apiUrl}/api/Upload/image`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        const data = JSON.parse(res.data)
        if (data.success) {
          this.sendMediaMessage('image', '', data.data.url, data.data.fileName, data.data.size)
        } else {
          wx.showToast({
            title: data.message || '上传失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 上传文件
  uploadFile(filePath, fileName, fileSize) {
    wx.showLoading({ title: '上传中...' })
    
    wx.uploadFile({
      url: `${app.globalData.apiUrl}/api/Upload/file`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        const data = JSON.parse(res.data)
        if (data.success) {
          this.sendMediaMessage('file', '', data.data.url, fileName, fileSize)
        } else {
          wx.showToast({
            title: data.message || '上传失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 处理文件下载
  handleDownloadFile(fileUrl, fileName) {
    wx.showLoading({ title: '下载中...' })
    
    wx.downloadFile({
      url: fileUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              wx.showToast({
                title: '下载成功',
                icon: 'success'
              })
            },
            fail: () => {
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 发送媒体消息
  sendMediaMessage(messageType, content, mediaUrl, fileName, fileSize) {
    if (!this.data.sessionId) return
    
    const message = {
      sessionId: this.data.sessionId,
      messageType: messageType,
      content: content,
      mediaUrl: mediaUrl,
      fileName: fileName,
      fileSize: this.formatFileSize(fileSize)
    }
    
    // 通过WebSocket发送
    wx.sendSocketMessage({
      data: JSON.stringify({
        type: 'SendMessage',
        sessionId: this.data.sessionId.toString(),
        message: message
      })
    })
  },

  // 格式化文件大小
  formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url],
      current: url
    })
  },

  // 下载文件事件处理
  downloadFile(e) {
    const { url, name } = e.currentTarget.dataset
    this.handleDownloadFile(url, name)
  },

  // 切换快捷回复显示
  toggleQuickReplies() {
    this.setData({
      showQuickReplies: !this.data.showQuickReplies
    })
  },

  // 输入框内容变化
  onInputChange(e) {
    this.setData({ inputText: e.detail.value })
  },

  // 滚动到底部
  scrollToBottom() {
    if (this.data.messages.length > 0) {
      const lastMessageId = `msg-${this.data.messages[this.data.messages.length - 1].id}`
      this.setData({ scrollIntoView: lastMessageId })
    }
  },

  // 格式化时间
  formatTime(time) {
    const date = new Date(time)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) return '刚刚'
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
    
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    
    return `${month}/${day} ${hour}:${minute}`
  },

  // 标记消息已读
  markMessageAsRead(messageId) {
    if (!this.data.sessionId) return
    
    // 通过WebSocket标记消息已读
    wx.sendSocketMessage({
      data: JSON.stringify({
        type: 'MarkMessageAsRead',
        messageId: messageId
      })
    })
  },

  // 标记会话所有消息已读
  markSessionMessagesAsRead() {
    if (!this.data.sessionId) return
    
    // 通过WebSocket标记会话消息已读
    wx.sendSocketMessage({
      data: JSON.stringify({
        type: 'MarkSessionMessagesAsRead',
        sessionId: this.data.sessionId
      })
    })
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      waiting: '等待客服接入...',
      active: '客服已接入',
      closed: '会话已结束'
    }
    return statusMap[status] || ''
  }
})